﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Facebook;
using System.Threading;
using System.IO;
using System.Dynamic;
using System.Diagnostics;
//using DatabaseLayer;

namespace FacebookAccessLayer
{
    public class FacebookFunctions
    {
        private FacebookClient client;
        private String sSource = "Facebook Access Layer";
        private String sLog = "Application";
        
        private String applicationKey = "336508236381580";
        private String applicationSecret = "c4c5fb6554ca06e143cc7cfc11163f7c";
        private String redirectURI = "http://localhost/IVRJunctionUI/FacebookAccessToken.aspx";

        public FacebookFunctions()
        {

        }

        public Tuple<String, String, String> getFacebookConfigurations()
        {
            return Tuple.Create<String, String, String>(applicationKey, applicationSecret, redirectURI);
        }
        
        public String getAccessTokenFromCode(String code)
        {
            String accessTokenString = null;
            try
            {
                var facebookOAuthClient = new Facebook.FacebookOAuthClient();
                facebookOAuthClient.AppId = applicationKey;
                facebookOAuthClient.AppSecret = applicationSecret;
                facebookOAuthClient.RedirectUri = new Uri(redirectURI);

                dynamic result = facebookOAuthClient.ExchangeCodeForAccessToken(code);
                accessTokenString = result.access_token;

            }
            catch (FacebookOAuthException facebookOAuthException)
            {
                EventLog.WriteEntry(sSource, "Error converting code to access token:" + facebookOAuthException.Message, EventLogEntryType.Error);
            }

            return accessTokenString;

        }

        public Uri getAccessTokenFromOAuth(String appId, String appSecret, String redirectURL)
        {
            Uri loginUri = null;
            try
            {
                FacebookOAuthClient client = new FacebookOAuthClient();
                client.AppId = appId;
                client.AppSecret = appSecret;
                client.RedirectUri = new Uri(redirectURL);
                
                
                var parameters = new Dictionary<string, object>
                    {
                        //{ "response_type", "token" },
                        { "display", "popup" }
                    };
                // If the application has obtained offline_access permission from the user, the access token does not have an expiry. 
                //However it gets invalidated whenever the user changes his/her password or user declines the permission to application.

                //string[] extendedPermissions = new[] { "publish_stream", "offline_access" };
                //if (extendedPermissions != null && extendedPermissions.Length > 0)
                //{
                //    var scope = new StringBuilder();
                //    scope.Append(string.Join(",", extendedPermissions));
                //    parameters["scope"] = scope.ToString();
                //}

                //String extendedPermissions = "offline_access,publish_stream";
                String extendedPermissions = "offline_access,publish_stream,manage_pages";

                if (!string.IsNullOrEmpty(extendedPermissions))
                {
                    // A comma-delimited list of permissions
                    parameters["scope"] = extendedPermissions;
                }
               
                loginUri = client.GetLoginUrl(parameters);
                
            }
            catch (Exception errorMessage)
            {
                // log this event in logger
                EventLog.WriteEntry(sSource, "Error in getting access token from OAuth:"+errorMessage.Message, EventLogEntryType.Error);
            }

            return loginUri;
        }

     
        public bool uploadTestStatus(String accessToken)
        {
            bool uploadSuccess = false;
            try
            {
                String pageURI = "https://graph.facebook.com/me/accounts?access_token=";
                pageURI = pageURI + accessToken;
                client = new FacebookClient(accessToken);
                dynamic objectPage = client.Get(pageURI);
                String pageAccessToken = objectPage.data[0].access_token;
                String pageId = objectPage.data[0].id;


                dynamic parameters = new ExpandoObject();
                
                parameters.access_token = pageAccessToken;


                parameters.message = "This is a test upload message";
                //parameters.name = "Article Title";
                //parameters.description = "Longer description of the link";
                /* This can not be used when pushing data on the facebook page
                parameters.privacy = new
                {
                    value = "ALL_FRIENDS",
                };
                */
                //dynamic result1 = client.Post("me/feed", parameters);
                dynamic result1 = client.Post("/" + pageId + "/feed", parameters);
                
                uploadSuccess = true;
            }
            catch (Exception errorMessage)
            {
                // log the exception
                EventLog.WriteEntry(sSource, "Error uploading test status:" + errorMessage.Message, EventLogEntryType.Error);

            }

            return uploadSuccess;

        }
        
        /* This is the previous version to post something on user wall rather than on a page...
        public bool uploadTestStatus()
        {
            bool uploadSuccess = false;
            try
            {
                
                dynamic parameters = new ExpandoObject();
                parameters.message = "This is a test upload message";
                //parameters.name = "Article Title";
                //parameters.description = "Longer description of the link";
                parameters.privacy = new
                {
                    value = "ALL_FRIENDS",
                };
               
                dynamic result1 = client.Post("me/feed", parameters);
                //dynamic result1 = client.Post("/156038681192324/feed", parameters);

                uploadSuccess = true;
            }
            catch (Exception errorMessage)
            {
                // log the exception
                EventLog.WriteEntry(sSource, "Error uploading test status:"+errorMessage.Message, EventLogEntryType.Error);
                
            }

            return uploadSuccess;

        }
         * */

        public bool uploadLink(String title, String description, String youTubeVideoLink,String accessToken)
        {
            bool isUploadSuccess = false;

            try
            {
                String pageURI = "https://graph.facebook.com/me/accounts?access_token=";
                pageURI = pageURI + accessToken;

                client = new FacebookClient(accessToken); 

                dynamic objectPage = client.Get(pageURI);
                String pageAccessToken = objectPage.data[0].access_token;
                String pageId = objectPage.data[0].id;

                dynamic parameters = new ExpandoObject();

                parameters.access_token = pageAccessToken;

                parameters.message = title;
                parameters.link = youTubeVideoLink;
                parameters.name = title;
                //parameters.caption = "Caption for the link";
                parameters.description = description;
                
                dynamic result1 = client.Post("/" + pageId + "/feed", parameters);
                
                isUploadSuccess = true;

            }
            catch (FacebookOAuthException objectFacebookOAuthException)
            {
                // log this exception in the event logger
                EventLog.WriteEntry(sSource, "Error uploading link:"+objectFacebookOAuthException.Message, EventLogEntryType.Error);
            }
            catch (Exception generalException)
            {
                // log this exception in the event logger
                EventLog.WriteEntry(sSource, "Error uploading link:"+generalException.Message, EventLogEntryType.Error);
            }

            return isUploadSuccess;
        }
    }
}
